package spring.mvc.practice.controllers;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;

import spring.mvc.practice.*;




/**
 * Handles Login functions.
 */
@Controller
public class LoginController {
	
	
	
	
	@Autowired
	private AccountDao accountDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	

	@ResponseBody
	@RequestMapping(value = "/base/documentAjaxUpdate/getPasswordQuestion", method = RequestMethod.GET)
	public String getQuestion(@RequestParam("email") String email) {
				
		AccountBean account = accountDao.findByEmail(email);
		
		if (account == null)
			return "user not found";
		else
			return account.getQuestion();	
	}
	
	@ResponseBody
	@RequestMapping(value = "base/documentAjaxUpdate/verifyPasswordQuestion", method = RequestMethod.GET)
	public String verifyAnswer(@RequestParam("email") String email,
			                   @RequestParam("answer") String answer) {
					
		AccountBean account = accountDao.findByEmail(email);
		
		if (account == null || account.getAnswer() == null)
			return "Failed";
		else
			if (account.getAnswer().equals(answer)) 
			  return "Passed";
			  
		
		return "Failed";
			  
	}	
	
	@ResponseBody
	@RequestMapping(value = "base/documentAjaxUpdate/changePassword", method = RequestMethod.POST)
	public String changePassword(@RequestParam("email") String email,
			                     @RequestParam("answer") String answer,
			                     @RequestParam("pass") String pass)  {
						
				
		
		AccountBean account = accountDao.findByEmail(email);
		
		if (account == null || account.getAnswer() == null)
			return "Failed";
		else
			if (account.getAnswer().equals(answer)) {
				
				account.setPassword(passwordEncoder.encodePassword(pass, null));
				accountDao.changePassword(account);
				
				Authentication authentication = new UsernamePasswordAuthenticationToken(account,account.getPassword(),account.getAuthorities());
		    	SecurityContextHolder.getContext().setAuthentication(authentication);
				
				return "Passed";
			}
			  
			  
		
		return "Failed";
			  
	}	
			
}
